/**
 * 路由中间件
 *
 * 处理业务模块的路由
 * 新添加的业务模块先import引入
 * 如：import * as ctlSystem from 'src-ssr/controller/system';
 * 再把该模块添加到modules中
 * 如：
 * const modules = {
 *   ...
 *   system: ctlSystem,
 *   ...
 * }
 * 路由规则见下面的功能功能路由规则说明。
 */
import { ssrMiddleware } from 'quasar/wrappers'
import jwt from 'jsonwebtoken';
import formidable from 'formidable';
import path from 'path';
import fs from 'fs';
import sharp from 'sharp';
import moment from 'moment';
import * as tools from 'src-ssr/util/common';

import * as ctlSystem from 'app/src-ssr/controller/system';
import * as ctlLogin from 'app/src-ssr/controller/login';
import * as ctlShare from 'app/src-ssr/controller/share';
import * as ctlShop from 'app/src-ssr/controller/shop';
import ctlManager from 'app/src-ssr/controller/manager';
import ctlTenant from 'app/src-ssr/controller/tenant';

const modules = {
  system: ctlSystem,
  login: ctlLogin,
  manager: ctlManager,
  tenant: ctlTenant,
  share: ctlShare,
  shop: ctlShop
};

// "async" is optional;
// more info on params: https://v2.quasar.dev/quasar-cli/developing-ssr/ssr-middlewares
export default ssrMiddleware(async ({ app /*, resolveUrlPath, publicPath, render */ }) => {
  // something to do with the server "app"
  /* 检查jwt有效性 */
  app.use('/checkToken', (req, res, next) => {
    let { token } = req.body;
    token = token.split(' ');

    if (token.length < 2) {
      res.send('Unauthorized');
    } else {
      jwt.verify(token[1], global.privateKey, (err, decoded) => {
        if (err) { // 过期
          res.send('Unauthorized');
        } else {
          res.send('Authorized');
        }
      });
    }
  });

  /**
   * 三级路由
   * 规则：
   *     路由：./controller/module:action，
   *     :mdl 模块名称
   *     :act 接口函数
   */
  app.use('/c/:mdl/:act', (req, res, next) => {
    const { mdl, act } = req.params;
    try {
      modules[mdl][act](req, res);
    } catch (e) {
      console.error(`An error occurred while requesting /c/${mdl}/${act}.`, e);
      res.status(404).send(`Sorry, we cannot find module /c/${mdl}/${act}!`);
    }
  });

  /**
   * 四级路由
   * 规则：
   *     :mdl 模块名称
   *     :bus 业务名称
   *     :act 接口函数
   */
  app.use('/c2/:mdl/:bus/:act', (req, res, next) => {
    const { mdl, bus, act } = req.params;
    try {
      modules[mdl][bus][act](req, res);
    } catch (e) {
      console.error(`An error occurred while requesting /c2/${mdl}/${bus}/${act}.`, e);
      res.status(404).send(`Sorry, we cannot find module /c2/${mdl}/${bus}/${act}!`);
    }
  });

  /* 文件上传 */
  app.post('/upload', async (req, res) => {
    // 上传路径：uploads/tid/YYYYMM/
    const user = await tools.getLoginUser(req.get('Authorization').split(' ')[1]);

    const dir = process.env.DEV ? '../..' : '..';
    const rootFolder = path.join(path.resolve(__dirname, dir), 'uploads');

    if (!fs.existsSync(rootFolder)) {
      fs.mkdirSync(rootFolder)
    }

    // 当月目录
    const YYYYMM = moment().format('YYYYMM');
    const folder = path.join(rootFolder, String(user.tid), YYYYMM);
    if (!fs.existsSync(folder)) {
      // fs.mkdirSync(folder);
      tools.mkdirs(folder);
    }
    // 缩略图目录
    const thumbFolder = path.join(folder, 'thumb');
    if (!fs.existsSync(thumbFolder)) {
      fs.mkdirSync(thumbFolder)
    }

    const form = formidable({
      uploadDir: folder,
      keepExtensions: true,
      maxFieldsSize: 100 * 1024 * 1024 // 限制上传100M
    });

    form.parse(req, (err, fields, files) => {
      if (err) {
        return res.json({ result: 'fail', message: err });
      }
      // console.log('\n-----------')
      // console.log('Fields', fields)
      // console.log('Received:', files)
      const images = [];
      const attachs = []; // 返回文件列表 type: 'application/pdf' type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      for (const key in files) {
        const fileItem = Object.prototype.toString.call(files[key]) === '[object Array]' ? files[key][0] : files[key];
        if (fileItem.mimetype.indexOf('image/') >= 0) { // 图片类型
          let filepath = fileItem.filepath;
          const extname = path.extname(filepath);
          // 没有后缀名，增加后缀名
          if (!extname && fileItem.mimetype.indexOf('/png;') >= 0) {
            filepath = filepath + '.png';
            fs.renameSync(fileItem.filepath, filepath);
          }
          // 生成缩略图
          const thumbPath = path.join(thumbFolder, path.basename(filepath))
          sharp(filepath)
            .resize(400, 400, {
              fit: sharp.fit.inside,
              withoutEnlargement: true
            })
            .toFile(thumbPath, (err) => {
              err && console.log(err);
            });
          images.push({
            filename: key,
            url: `/uploads/${String(user.tid)}/${YYYYMM}/` + path.basename(filepath),
            thumb: `/uploads/${String(user.tid)}/${YYYYMM}/thumb/` + path.basename(filepath),
            size: fileItem.size
          });
        } else { // 文件类型 if (files[key].type.indexOf('application/') >= 0)
          attachs.push({
            filename: key,
            url: `/uploads/${String(user.tid)}/${YYYYMM}/` + path.basename(fileItem.filepath),
            size: fileItem.size,
            type: fileItem.mimetype
          });
        }
      }

      res.json({
        result: 'ok',
        images,
        attachs
      });
    });
  });
});
